<?php

/**
 * Staffs Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  MIAOCMS
 * @version  1.0
 * @author   Arlon <MIAOCMS@google.com>
 * @link     http://www.MIAOCMS.net
 */
class StaffsController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    var $name = 'Staffs';
    var $components = array(
        'Email',
        'Kcaptcha',
    	'Cookie' => array('name' => 'MIAOCMS', 'time' => '+2 weeks'),
        //'Securimage',
    );
    
    var $uses = array('Staff','User');

    function beforeFilter() {
        parent::beforeFilter();
    }

    function admin_captcha() {
        error_reporting(0);
        $this->Kcaptcha->render();
    }

    function admin_add() {
        if (!empty($this->data['Staff']['password'])) {
            $this->data['Staff']['password'] = AuthComponent::password($this->data['Staff']['password']);
        }
        parent::admin_add();
        
        if($this->insert_id){ // 新增成功时
        	if(empty($this->data['Staff']['user_id'])){ //front_password
        		$this->loadModel('User');
        		$this->User->create();
        		$this->User->save(array(
    				'username' => $this->data['Staff']['name'],
        			'password' => AuthComponent::password($this->data['Staff']['front_password']),
        			'email' => $this->data['Staff']['email'],
        			'role_id' => Configure::read('User.defaultroler'),
        		));
        		$user_id = $this->User->getLastInsertID();
        		
        		$this->Staff->updateAll(array('user_id'=>$user_id),array('Staff.id'=>$this->insert_id));
        	}
        }
    }
    
    function admin_edit($id='' ,$copy = null) {
        if (!$id) {
            $id = $this->_getParamVars('id');
        }

        if (empty($_POST['data'][$this->modelClass]['password'])) {
            // 当post提交空密码时，不修改密码。修改用户资料，输入了新密码时，修改密码；无输入密码时不修改密码。
            unset($this->data[$this->modelClass]['password']);
        } else {
            $this->data[$this->modelClass]['password'] = AuthComponent::password($this->data[$this->modelClass]['password']);
        }
        parent::admin_edit($id,$copy);
        if(!empty($this->data['Staff']['user_id']) && !empty($this->data['Staff']['front_password'])){
        	$this->loadModel('User');
        	$this->User->create();
        	$this->User->recursive = -1;
        	$this->User->updateAll(array(        			
        			'password' =>  $this->User->escape_string( AuthComponent::password($this->data['Staff']['front_password']) ),
        	),array(        			
        			'User.id' => $this->data['Staff']['user_id'],
        	));
        	// acl权限控制相关的，不能使用save方法修改部分字段的值，要使用updateALL.
        	
//         	$this->User->save(array(        			
//         			'password' => AuthComponent::password($this->data['Staff']['front_password']),
//         			'id' => $this->data['Staff']['user_id'],
//         	),true,array('password'));
        }
        unset($this->data[$this->modelClass]['password']);
    }

    function admin_reset_password($id = null) {
        if (!$id && empty($this->data)) {
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->redirect(array('action' => 'index'));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
    }

    function admin_login() {
        $this->pageTitle = __('Admin Login', true);
        if(preg_match('/MSIE 6.0/i',$_SERVER['HTTP_USER_AGENT'])){
        	$this->layout = 'ie6';
        }
        else{
        	$this->layout = 'admin_login';
        }
        if ($id = $this->Auth->user('id')) { // //已有session登录信息，自动登录
            $userinfo = $this->Auth->user();
            if(!is_array($userinfo['role_id'])){
            	$this->data['role_id'] = array_delete_value(explode(',',$userinfo['role_id']));
            }
            else{
            	$this->data['role_id'] = $userinfo['role_id'];
            }
            $this->Staff->id = $id;
            $this->Staff->updateAll(array(
                'last_login' => "'".date('Y-m-d H:i:s')."'"
            ),array('Staff.id' => $id));
            $redirect = $this->Auth->redirect();
            if (strpos($redirect, 'login') !== false || strpos($redirect, 'admin/staffs') !== false) {
                $redirect = '/admin/systems/index';
            }
            $this->redirect($redirect);
        }
        else{
        	$cookie_user = $this->Cookie->read('Auth.Staff');
        	if (is_array($cookie_user) && !empty($cookie_user['id'])) { //已有cookie登录信息，自动登录
        		
        		$staffinfo = $this->Staff->findById($cookie_user['id']);
        		
        		// 验证cookie的有效时间。不能大于用户信息更新的时间。
        		if( !empty($staffinfo['Staff']) && $staffinfo['Staff']['updated'] < $cookie_user['last_login'] ) {
        		    if(!is_array($staffinfo['Staff']['role_id'])){
        		        $staffinfo['Staff']['role_id'] = array_delete_value(explode(',',$staffinfo['Staff']['role_id']));
        		    }
        		    $this->Session->write('Auth.Staff', $staffinfo['Staff']);
        		    
        		    $this->Staff->updateAll(array(
        		        'last_login' => "'".date('Y-m-d H:i:s')."'"
        		    ),array('Staff.id' => $cookie_user['id']));
        		    
        		    if( !empty($staffinfo['Staff']['user_id']) ){
        		        //设置前台用户登录信息
        		        $this->loadModel('User');
        		        $front_userinfo = $this->User->find('first',array(
        		            'conditions'=> array('id'=>$staffinfo['Staff']['user_id']),
        		            'recursive' => 1,
        		        ));
        		        $this->Session->write('Auth.User',$front_userinfo['User']);
        		        $this->Session->write('Auth.User.Role',$front_userinfo['Role']);
        		    }
        		    
        		    
        		    $redirect = $this->Auth->redirect();
        		    if(strpos($redirect, 'login') !== false || strpos($redirect, 'admin/staffs') !== false || in_array($redirect,array('/admin','/admin/','','/'))) {
        		        $redirect = '/admin/systems/index'; //防止跳转到/admin，当成了一个栏目地址
        		    }
        		    $this->redirect($redirect);
        		    
        		}
        	}
        }
                

        if (!empty($this->data['Staff'])) { // 有提交时，验证登录
            
            if ($this->Auth->login()) {
            	$userinfo = $this->Auth->user();
                $id = $this->Staff->id = $userinfo['id'];
                if(!is_array($userinfo['role_id'])) {
                    $userinfo['role_id'] = array_delete_value(explode(',',$userinfo['role_id']));
                }

                $this->Session->write('Auth.Staff.role_id',$userinfo['role_id']);
                
                $this->Staff->updateAll(array(
                    'last_login' => "'".date('Y-m-d H:i:s')."'",
                ),array('Staff.id' => $id));
                if ( !empty($this->data['Staff']['remember_me']) ) {
                	$this->Cookie->write('Auth.Staff', $this->Session->read('Auth.Staff'), true, 31536000);
                }
                else{
                    $this->Cookie->write('Auth.Staff', $this->Session->read('Auth.Staff'), true, 0);
                }
                
                $staffinfo = $this->Staff->findById($id);
                if(!empty($staffinfo['Staff']['user_id'])){
                	//设置前台用户登录信息
                	$this->loadModel('User');
                	$front_userinfo = $this->User->getUserInfo( $staffinfo['Staff']['user_id'] );
                	$this->Session->write('Auth.User',$front_userinfo['User']);
                }
                $redirect = $this->Auth->redirect();
                if(in_array($redirect,array('/admin','/admin/','','/'))) {
                    $redirect = '/admin/systems/index'; //防止跳转到/admin，当成了一个栏目地址
                }
                $this->redirect($redirect);
            } else {
                unset($this->data['Staff']['password']);
                $this->Session->setFlash(__('username or password not right'));
            }
        }
    }

    function admin_logout() {
        $this->Cookie->destroy();
        $this->Session->destroy();
        $this->Auth->logout();
        $this->redirect('/admin/');
    }

    function admin_editpassword() {
        $userinfo = $this->Auth->user();
        if (!$userinfo['id']) {
            $this->Session->setFlash(__('You are not authorized to access that location.', true));
            $this->redirect(array('action' => 'login'));
        }
        if (!empty($this->data) && isset($this->data['Staff']['password'])) {
            $before_edit = $this->{$this->modelClass}->read(null, $userinfo['Staff']['id']);

            if ($before_edit['Staff']['password'] == Security::hash($this->data['Staff']['password'], null, true)) {

                if (!empty($this->data['Staff']['new_password']) && $this->data['Staff']['new_password'] == $this->data['Staff']['password_confirm']) {
                    $user = array();
                    $user['Staff']['id'] = $userinfo['Staff']['id'];
                    $user['Staff']['password'] = Security::hash($this->data['Staff']['new_password'], null, true);
                    $user['Staff']['activation_key'] = md5(uniqid());

                    if ($this->Staff->save($user['Staff'])) {
                        $this->Session->setFlash(__('Password is updated success.', true));
                    }
                } else {
                    $this->Session->setFlash(__('Two password is empty or not equare.', true));
                }
            } else {
                $this->Session->setFlash(__('Your password is not right.', true));
            }
        } else {
            $this->Session->delete('Message.flash');
        }
    }

}

?>